package tcp.chat;
//接收

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 1.创建TCP协议的socket套接字和ServerSocket指点端口
 * 2.接收套接字
 * 3.创建管道流，并且不数据放入管道流中
 * 4.打印信息
 * 5.关闭资源
 */
public class tcp_receive extends Thread {
    private ServerSocket socket = null;
    private Socket accept = null;
    private InputStream Input = null;
    private ByteArrayOutputStream Output = null;
    private int post;

    public tcp_receive(int post) {
        this.post = post;
    }

    @Override
    public void run() {
        try {
            socket = new ServerSocket(post);
            System.out.println("等待信息...............");
            while (true) {
                accept = socket.accept();
                System.out.println("监听到信息......");
                Input = accept.getInputStream();
                System.out.println("接收到信息流..........");
                Output = new ByteArrayOutputStream();
                System.out.println("创建成功管道流..........");
                byte[] xx = new byte[1024];
                int len;
                System.out.println("获取信息中........");
                System.out.println("写入管道流中.............");
                while ((len = Input.read(xx)) != -1) {//Input.read(xx)从输入流读取一些字节数，并将它们存储到缓冲区 b 。返回位-1时读取完
                    Output.write(xx, 0, len);//从指定的字节数组写入 len字节，从偏移量为 off开始，输出到这个字节数组输出流。
                    System.out.println("写入数据成功.............");
                }
                System.out.println(Output.toString());
                if (Output.toString().matches(".*bey.*")){
                    System.out.println("对方下线了");
                    break;
                }
            }
        } catch (
                IOException e) {
            e.printStackTrace();
        } finally {

            try {
                if (Output != null) {
                    Output.close();
                }
                if (Input != null) {
                    Input.close();
                }
                if (accept != null) {
                    accept.close();
                }
                if (socket != null) {
                    socket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
